package utils;

import javax.servlet.http.HttpSession;
import java.util.Random;

public class CaptchaService {

    private static final String CAPTCHA_KEY = "captcha";

    public String generateCaptcha(HttpSession session) {
        // 生成验证码
        Random random = new Random();
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            captcha.append(random.nextInt(10));
        }

        // 存储验证码到Session
        session.setAttribute(CAPTCHA_KEY, captcha.toString());

        // 设置Session的超时时间为60秒
        session.setMaxInactiveInterval(60);

        return captcha.toString();
    }

    public boolean validateCaptcha(HttpSession session, String inputCaptcha) {

        // 从Session中获取验证码
        String sessionCaptcha = (String) session.getAttribute(CAPTCHA_KEY);

        // 验证验证码是否匹配
        if (sessionCaptcha != null && sessionCaptcha.equals(inputCaptcha)) {
            // 验证码匹配，可以进一步处理
            return true;
        } else {
            // 验证码不匹配，返回false
            return false;
        }
    }
}